package engine.io;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class Reader {
	
	// TODO throw errors instead of system.exit
	private DocumentBuilder db;
	
	/*
	 * Creates a reusable DocumentBuilder.
	 * Terminal error if DB can't be instantiated.
	 */
	public Reader() {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		try {
			db = factory.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			System.err.println("Could not create DocumentBuilder: " +
					e.getMessage());
			System.exit(-1);
		}
	}
	
	/*
	 * Returns DOM of XML file.
	 * @param filename The path to XML file.
	 * @return the DOM of the XML file.
	 * @throws SAXException if there is any parsing error.
	 * @throws IOException if there is any error reading the file.
	 */
	public Document getDocument(String filename) throws SAXException, IOException {
		File file = new File(filename);
		Document doc = db.parse(file);
		return doc;
	}
}
